<template>
  <Category :scene="scene"></Category>
  <el-card style="margin: 10px 0px">
    <div v-show="scene == 0">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="categoryStore.c3Id ? false : true"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0px" :data="attrArr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          width="120px"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row }">
            <el-tag
              style="margin: 5px"
              v-for="item in row.attrValueList"
              :key="item.id"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row }">
            <!-- 修改已有属性的按钮 -->
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定删除${row.attrName}?`"
              width="200px"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加与修改属性 界面 -->
    <div v-show="scene == 1">
      <!-- 展示添加属性与修改数据的结构 -->
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请你输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        @click="addAttrValue"
        :disabled="attrParams.attrName ? false : true"
        type="primary"
        size="default"
        icon="Plus"
      >
        添加属性值
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-table
        border
        style="margin: 10px 0px"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          label="序号"
          width="80px"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-input
              :ref="(vc: any) => inputArr[$index] = vc"
              v-if="row.flag"
              @blur="toLook(row, $index)"
              size="small"
              placeholder="请你输入属性值名称"
              v-model="row.valueName"
            ></el-input>
            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #="{ index }">
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="attrParams.attrValueList.splice(index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        size="default"
        @click="save"
        :disabled="attrParams.attrValueList.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue';
//获取属性的接口
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr';
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from '@/api/product/attr/type';
//引入分类相关的仓库
import useCategoryStore from '@/store/modules/category';
import { ElMessage } from 'element-plus';
let categoryStore = useCategoryStore();

//存储已有的属性与属性值
let attrArr = ref<Attr[]>([]);
//定义card组件内容展示 0显示table，1显示属性添加与修改属性界面
let scene = ref<number>(0);

//收集新增属性的数据
let attrParams = reactive<Attr>({
  attrName: '', //新增属性的名字
  attrValueList: [], //新增的属性值数组
  categoryId: '', //三级分类id
  categoryLevel: 3, //分类等级
});

//准备一个数组:将来存储对应的组件实例el-input  给ref一个方法，组件实例数据改变时会调用
let inputArr = ref<any>([]);

//当组件销毁，清空仓库相关数据
onBeforeUnmount(() => {
  categoryStore.$reset();
});

//监听仓库三级分类的变化
watch(
  () => categoryStore.c3Id,
  () => {
    //清空上次查询
    attrArr.value = [];
    //三级分类不为空才发请求
    if (!categoryStore.c3Id) return;
    //获取分类id
    getAttr();
  },
);
//获取的属性与属性值
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  //获取分类下已有的属性与属性值
  let res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (res.code == 200) {
    attrArr.value = res.data;
  }
};

//添加属性 回调
const addAttr = () => {
  // 清空一下收集的新增属性
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.c3Id, //顺便保存三级分类id，用于添加属性
    categoryLevel: 3,
  });
  //切换到添加修改界面
  scene.value = 1;
};
//table表格修改按钮 回调
const updateAttr = (row: Attr) => {
  //切换到添加修改界面
  scene.value = 1;
  //将已有的属性对象赋值给attrParams对象即为
  //ES6->Object.assign进行对象的合并
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};

//取消按钮的回调
const cancel = () => {
  scene.value = 0;
};

//删除属性的回调
const deleteAttr = async (attrId: number) => {
  let res = await reqRemoveAttr(attrId);
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
    getAttr();
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    });
  }
};

//添加属性界面
//添加属性按钮 回调
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    //控制添加属性页面文本框编辑模式和查看模式切换
    flag: true,
  });

  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};
//保存按钮 回调
const save = async () => {
  let res = await reqAddOrUpdateAttr(attrParams);
  //保存成功，切换场景
  if (res.code == 200) {
    scene.value = 0;
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    });
    getAttr();
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    });
  }
};

//文本框编辑和查看模式切换
const toLook = (row: AttrValue, $index: number) => {
  //非法情况判断
  if (row.valueName.trim() === '') {
    //删除这个属性
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    });
    return;
  }
  //非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    //排除自己
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    //干掉这条属性
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    });
  }

  row.flag = false;
};
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true;

  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
</script>

<style scoped></style>
